/*
 * =====================================================================================
 *
 *       Filename:  socket.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  07/20/2012 09:01:07 PM
 *       Revision:  none
 *       Compiler:  gcc/g++
 *
 *         Author:  wangtengchao , wangtengchao AT gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */

#include"socket.h"
#include"netHelp.h"
#include"inetAddr.h"
#include<netinet/tcp.h>
using namespace inm::net;

Socket::Socket()
{
#ifdef linux
    sockfd_ = inm::net::Socket(AF_INET,SOCK_STREAM,0);
#else
    sockfd_ = inm::net::Socket(PF_INET,SOCK_STREAM,0);
#endif
    inm::net::SetNonBlock(sockfd_);
    isBind_ = false;
}
Socket::Socket(const InetAddr &serverAddr)
{
#ifdef linux
    sockfd_ = inm::net::Socket(AF_INET,SOCK_STREAM,0);
#else
    sockfd_ = inm::net::Socket(PF_INET,SOCK_STREAM,0);
#endif
    inm::net::SetNonBlock(sockfd_);
    inm::net::Bind(sockfd_,serverAddr.getSockAddr());//bind
    isBind_ = false;
}

Socket::~Socket()
{
    inm::net::Close(sockfd_);
}

void Socket::bind(const InetAddr &serverAddr)
{
    if(!isBind_)
     {//if not use constructor "Socket(const InetAddr &serverAddr)" to bind
        inm::net::Bind(sockfd_,serverAddr.getSockAddr());
        isBind_ = true;
    }

}
int Socket::accept(InetAddr &clientAddr)
{
   return  inm::net::Accept(sockfd_,clientAddr);
}
void Socket::listen()
{
    inm::net::Listen(sockfd_);
}
void Socket::setNoDelay(bool b)
{
	int optval = 0;
	if(b)
		optval = 1;//open Nagle
	if(setsockopt(sockfd_,IPPROTO_TCP,TCP_NODELAY,&optval,sizeof(optval)) < 0)
	{//error

	}
}
